package com.litelimit.core.strategy.impl;

import com.litelimit.core.limit.annotation.LiteLimit;
import com.litelimit.core.service.loader.LuaScriptLoader;
import com.litelimit.core.strategy.core.AbstractLimitStrategy;
import com.litelimit.core.strategy.core.LimitMethod;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 根据ip限流
 */
public class IpAbstractLimitStrategy extends AbstractLimitStrategy {

    public IpAbstractLimitStrategy(StringRedisTemplate stringRedisTemplate, LuaScriptLoader luaScriptLoader) {
        super(stringRedisTemplate, luaScriptLoader);
    }

    @Override
    public LimitMethod getLimitMethod() {
        return LimitMethod.LIMIT_IP;
    }

    @Override
    public boolean tryAcquire(LiteLimit limit) {
        String key = super.keyPrefix;
        if ("".equals(limit.group())) {
            key += getClientIp();
        } else {
            key += (limit.group() + ":" + getClientIp());
        }
        return super.doLimit(limit, key);
    }

    private String getClientIp() {
        // 获取当前请求属性（绑定到当前线程）
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 从请求属性中获取 HttpServletRequest
        HttpServletRequest request = attributes.getRequest();
        // 获取 IP 地址（无代理时直接返回）
        return request.getRemoteAddr();
    }
}
